package org.opens.javaskill.thread.demo.bank;

import java.util.Random;

/**
 * 说明:
 *      1. 使用Runnable接口相当于是将业务逻辑和功能实现分离了.
 */
public class TicketWindowUseRunnable implements Runnable {

    // 最大服务数量
    private final int MAX = 50;

    // 起始号码
    private int index = 1;

    @Override
    public void run() {
        Random random = new Random();
        while ( index <= MAX ) {
            System.out.println("柜台: " + Thread.currentThread().getName() + ", 当前的号码是: " + (index++));
            try {
                Thread.sleep(random.nextInt(3) * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final TicketWindowUseRunnable windowUseRunnable = new TicketWindowUseRunnable();
        Thread thread1 = new Thread(windowUseRunnable, "窗口1");
        Thread thread2 = new Thread(windowUseRunnable, "窗口2");
        Thread thread3 = new Thread(windowUseRunnable, "窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class SyncTicketWindowUseRunnable implements Runnable {

    private final static Object MONITOR = new Object();

    // 最大服务数量
    private final int MAX = 50;

    // 起始号码
    private int index = 1;

    @Override
    public void run() {
        Random random = new Random();
        while ( index <= MAX ) {
            synchronized (MONITOR) {
                System.out.println("柜台: " + Thread.currentThread().getName() + ", 当前的号码是: " + (index++));
            }
            try {
                Thread.sleep(random.nextInt(3) * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        final SyncTicketWindowUseRunnable ticketWindowUseRunnable = new SyncTicketWindowUseRunnable();

        Thread thread1 = new Thread(ticketWindowUseRunnable, "窗口1");
        Thread thread2 = new Thread(ticketWindowUseRunnable, "窗口2");
        Thread thread3 = new Thread(ticketWindowUseRunnable, "窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}